<?php
/**
 * Created by PhpStorm.
 * User: Aaron
 * Date: 2019/7/18
 * Time: 15:09
 */
namespace Inters\Controller;

use Think\Controller;
use Inters\Model\MemberModel;

class BaseController extends Controller
{
    public function __construct()
    {
        if ($GLOBALS['_SERVER']['REQUEST_METHOD'] == "OPTION") {
            exit("option请求失败");
        }


        // 跨域请求
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Headers:*');
        header('Access-Control-Allow-Methods:*');
        header('Content-type:application/json');
        parent::__construct();
    }

    /**
     *  获取token
     */
    public function tokenShiftMemberId()
    {
        $this->member_id = $this->read_token($_SERVER['HTTP_TOKEN']);
    }


    // 统一返回
    public function _json($code = 200, $data = array(), $message = "")
    {
        $result = array(
            "code"    => $code,
            "data"    => $data,
            "message" => $message
        );

        return json_encode($result);
    }

    /**
     * 创建token
     */
    protected function create_token($id)
    {
        $mm = new MemberModel();

        // 读取token
        $mm->readTokenClear($id);

        $rand = md5(rand(1000, 99999).$id);
        S($rand, $id, C('EXPIRE'));

        // 写入token
        $mm->writeToken($id, $rand);

        return $rand;
    }

    /**
     *  读取token
     */
    protected function read_token($token)
    {
        return S($token);
    }

    /**
     *  删除token
     */
    protected function delete_token($token)
    {
        $mm = new MemberModel();
        $mm->clearToken($token);

        S($token, null);
    }


    /**
     * 鉴权
     */
    protected function requestAuth()
    {
        $get_token = I('get.token');
        $post_token = I('post.token');
        $header_token = $_SERVER['HTTP_TOKEN'];

        $token = empty($get_token) ? empty($post_token) ? $header_token : $post_token : $get_token;
        if (empty($token)){
            return false;
        }
        return $this->read_token($token);
    }


    /**
     *  Get请求
     */
    protected function curlGet($url = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}